package com.yeswater.mianshiyang.model.dto.question;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.yeswater.mianshiyang.model.entity.Question;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;

import java.util.Date;
import java.util.List;

@Document(indexName = "question")
@Data
public class QuestionEsDTO {

    public static final String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:dd";

    @Id
    private Long id;

    private String title;

    private String content;

    private String answer;

    private List<String> tags;

    private Long userId;

    @Field(type = FieldType.Date, format = {}, pattern = DATE_TIME_PATTERN)
    private Date createTime;

    @Field(type = FieldType.Date, format = {}, pattern = DATE_TIME_PATTERN)
    private Date updateTime;

    private Integer isDelete;

    public static final Long serialVersionUID = 1L;

    /**
     * 对象转包装类
     * @param question question
     * @return 包装类
     */
    public static QuestionEsDTO objToDto(Question question){
        if ( question == null) {
            return null;
        }
        QuestionEsDTO questionEsDto = new QuestionEsDTO();
        BeanUtils.copyProperties(question, questionEsDto);
        String tagsStr = question.getTags();
        if (StringUtils.isNotBlank(tagsStr)) {
            questionEsDto.setTags(JSONUtil.toList(tagsStr, String.class));
        }
        return questionEsDto;
    }

    /**
     * 包装类转对象
     * @param questionEsDto dto
     * @return question
     */
    public static Question dtoToObj(QuestionEsDTO questionEsDto){
        if ( questionEsDto == null) {
            return null;
        }
        Question question = new Question();
        BeanUtils.copyProperties(questionEsDto, question);
        List<String> tagList = questionEsDto.getTags();
        if (CollUtil.isNotEmpty(tagList)) {
            question.setTags(JSONUtil.toJsonStr(tagList));
        }
        return question;
    }

}
